package com.lyk.jsbridgeyuangong.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lyk.jsbridgeyuangong.BaseActivty;
import com.lyk.jsbridgeyuangong.Constant;
import com.lyk.jsbridgeyuangong.R;
import com.lyk.jsbridgeyuangong.http.MyOkhttp;
import com.lyk.jsbridgeyuangong.http.callback.StringNoDialogCallback;
import com.lyk.jsbridgeyuangong.http.request.BaseRequest;
import com.lyk.jsbridgeyuangong.httpmodel.LoginBean;
import com.lyk.jsbridgeyuangong.util.MySharePreferenceUtil;
import com.lyk.jsbridgeyuangong.util.Regular;
import com.lyk.jsbridgeyuangong.util.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/3/8.
 */

public class LoginActivity extends BaseActivty {


    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_top_layout)
    RelativeLayout rlTopLayout;
    @BindView(R.id.user_phone_num)
    EditText userPhoneNum;
    @BindView(R.id.img_clear_user)
    ImageView imgClearUser;

    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_messagelogin)
    TextView tvMessagelogin;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    @BindView(R.id.user_password)
    EditText userPassword;
    @BindView(R.id.img_clear)
    ImageView imgClear;
    @BindView(R.id.img_pass)
    ImageView imgPass;
    @BindView(R.id.li_opera)
    LinearLayout liOpera;
    String deviceId;
    private final String ACTION_NAME2 = "登录结束";
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_NAME2)) {
                Intent mIntent = new Intent(ACTION_NAME);
                mIntent.putExtra("yaner", "发送广播，相当于在这里传送数据");
                //发送广播
                sendBroadcast(mIntent);
                finish();
            }
        }

    };

    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTION_NAME2);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        deviceId = (String) MySharePreferenceUtil.get(LoginActivity.this, "deviceid", "");
        registerBoradcastReceiver();

        if (userPhoneNum.getText().toString().equals("")) {
            imgClearUser.setVisibility(View.GONE);
//            btnLogin.setEnabled(false);
//            btnLogin.setBackgroundResource(R.drawable.btn_unclick);
//            btn_login
        } else {
            imgClearUser.setVisibility(View.VISIBLE);
        }
        userPhoneNum.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (userPhoneNum.getText().toString().equals("")) {
                    imgClearUser.setVisibility(View.GONE);
//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
                } else {
                    imgClearUser.setVisibility(View.VISIBLE);
                }

                if (userPassword.getText().toString().equals("")) {

//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
//                    return;
                } else if (TextUtils.isEmpty(userPhoneNum.getText().toString())) {

//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
                } else if (!Regular.isMobileNO(userPhoneNum.getText().toString())) {

//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
                } else {
//                    btnLogin.setEnabled(true);
//                    btnLogin.setBackgroundResource(R.drawable.v6button);
                }


            }
        });

        userPassword.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (userPassword.getText().toString().equals("")) {
                    liOpera.setVisibility(View.GONE);
//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
                } else {
                    liOpera.setVisibility(View.VISIBLE);
                }
                if (userPassword.getText().toString().equals("")) {

//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
//                    return;
                } else if (TextUtils.isEmpty(userPhoneNum.getText().toString())) {

//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
                } else if (!Regular.isMobileNO(userPhoneNum.getText().toString())) {

//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
                } else {
                    btnLogin.setEnabled(true);
                    btnLogin.setBackgroundResource(R.drawable.v6button);
                }

            }
        });
    }


    @OnClick({R.id.img_back, R.id.rl_back, R.id.tv_title, R.id.rl_top_layout, R.id.user_phone_num, R.id.img_clear_user, R.id.btn_login, R.id.tv_messagelogin, R.id.tv_forget, R.id.user_password, R.id.img_clear, R.id.img_pass, R.id.li_opera})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_title:
                break;
            case R.id.rl_top_layout:
                break;
            case R.id.user_phone_num:
                break;
            case R.id.img_clear_user:
                userPhoneNum.setText("");
                break;

            case R.id.btn_login:
//                Toast.makeText(this, "登录了", Toast.LENGTH_SHORT).show();
                if (userPassword.getText().toString().equals("")) {
                    ToastUtil.showCenterToast(LoginActivity.this, "密码不能为空");
//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
//                    return;
                } else if (TextUtils.isEmpty(userPhoneNum.getText().toString())) {
                    ToastUtil.showCenterToast(LoginActivity.this, "手机号不能为空");
//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
                } else if (!Regular.isMobileNO(userPhoneNum.getText().toString())) {
                    ToastUtil.showCenterToast(LoginActivity.this, "手机号不符合规则");
//                    btnLogin.setEnabled(false);
//                    btnLogin.setBackgroundResource(R.drawable.btn_unclick);
                } /*else if (Regular.getPass(userPassword.getText().toString())) {
                    ToastUtil.showCenterToast(LoginActivity.this, "密码不符合规则");
                }*/ else {

                    btnLogin.setEnabled(true);
                    btnLogin.setBackgroundResource(R.drawable.v6button);
                    login();
                }


                break;
            case R.id.tv_messagelogin:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                finish();
                break;
            case R.id.tv_forget:

                startActivity(new Intent(LoginActivity.this, ForgetActivity.class));

                break;
            case R.id.user_password:
                break;
            case R.id.img_clear:
                userPassword.setText("");
                break;
            case R.id.img_pass:
                if (userPassword.getTransformationMethod().equals(PasswordTransformationMethod
                        .getInstance())) {
                    userPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    imgPass.setBackgroundResource(R.drawable.yan1);
                } else {
                    userPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    imgPass.setBackgroundResource(R.drawable.yan2);
                }
                break;
            case R.id.li_opera:
                break;
        }
    }

    private final String ACTION_NAME = "智投宝结束";

    public void login() {
        MyOkhttp.post(Constant.URL + "api/v1/system/login")
                .tag(this)
                .params("username", userPhoneNum.getText().toString())
                .params("password", userPassword.getText().toString())
                .params("did", deviceId)
                .params("deviceToken", "123455")
                .execute(new StringNoDialogCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        showLoading();

                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
//                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                        Gson gson = new Gson();
                        LoginBean loginBean = new LoginBean();
                        loginBean = gson.fromJson(s, LoginBean.class);
                        LoginBean.DataBean dataBean = loginBean.getData();
                        if (loginBean.getMeta().isSuccess() == false) {
//                            Toast.makeText(LoginActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            ToastUtil.showCenterToast(LoginActivity.this, loginBean.getMeta().getMessage());


                        } else {
//                            Toast.makeText(LoginActivity.this, "成功", Toast.LENGTH_SHORT).show();
                            ToastUtil.showCenterToast(LoginActivity.this, loginBean.getMeta().getMessage());
                            MySharePreferenceUtil.put(LoginActivity.this, "id", loginBean.getData().getId());
                            MySharePreferenceUtil.put(LoginActivity.this, "username", loginBean.getData().getUsername());
                            MySharePreferenceUtil.put(LoginActivity.this, "idCard", loginBean.getData().getIdCard());
                            MySharePreferenceUtil.put(LoginActivity.this, "token", loginBean.getData().getToken());

                            /*Intent intent = new Intent(LoginActivity.this, MainActivity.class);

                            intent.putExtra("url", "http://wbs.rmbboxs.cn/account/setting/verIdentity?token="+MySharePreferenceUtil.get(LoginActivity.this, "token", "")+"&app=true");
                            startActivity(intent);*/
                            Intent mIntent = new Intent(ACTION_NAME);
                            mIntent.putExtra("yaner", "发送广播，相当于在这里传送数据");
                            //发送广播
                            sendBroadcast(mIntent);
                            finish();
                        }


                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        Log.d(response.toString(), "333333333333");

                        Toast.makeText(LoginActivity.this, "error", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onAfter(String s, Exception e) {
                        super.onAfter(s, e);
                        dismissLoading();
                    }
                });
    }


}
